package com.mtgdeckbuilder.server.dao;

import java.util.List;
import java.util.logging.Logger;

import javax.persistence.EntityManager;

import com.google.appengine.api.datastore.Key;
import com.mtgdeckbuilder.server.EMF;

/**
 * The abstract class parent of all the Data Access Object.
 * http://code.google.com/p/sahab/source/browse/#svn%2Ftrunk%2Fsahab%2Fsrc%2Fcom%2Fsahab%2Fserver%2Fdao
 * 
 * @author Nicolas Deslandes
 * @param <T> The object handled by the implementation of this DAO.
 */
public abstract class DAO<T> {

   private static Logger logger = Logger.getLogger(DAO.class.getName());

   /**
    * Query a list from the database with the given arguments.
    * 
    * @param args the arguments.
    * @return the result list.
    */
   public abstract List<T> query(T args);

   /**
    * Save an entity in the database.
    * 
    * @param entity the entity to save.
    */
   public void save(final T entity) {
      logger.finest("Call of save(" + entity + ")");
      final EntityManager em = EMF.get().createEntityManager();
      try {
         em.persist(entity);
      } finally {
         em.close();
      }
   }

   /**
    * Fetch an entity from the database.
    * 
    * @param id the id of the entity to fetch.
    * @return the entity.
    */
   public abstract T fetch(final long id);

   /**
    * Fetch an entity from the database.
    * 
    * @param key the key of the entity to fetch.
    * @return the entity.
    */
   public abstract T fetch(final Key key);

}
